package com.tarena.lbs.service.impl;

import com.tarena.lbs.entity.CouponStock;
import com.tarena.lbs.mapper.CouponStockMapper;
import com.tarena.lbs.service.CouponStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CouponStockServiceImpl implements CouponStockService {

    @Autowired
    private CouponStockMapper couponStockMapper;

    @Override
    public CouponStock getStockByCouponId(Integer couponId) {
        return couponStockMapper.getStockByCouponId(couponId);
    }

    @Override
    @Transactional
    public boolean updateStock(Integer couponId, Integer num) {
        int result = couponStockMapper.updateStock(couponId, num);
        return result > 0;
    }

    @Override
    @Transactional
    public boolean decreaseStock(Integer couponId, Integer num) {
        // 检查库存是否足够
        CouponStock stock = getStockByCouponId(couponId);
        if (stock == null || stock.getNum() < num) {
            return false;
        }
        // 扣减库存
        return updateStock(couponId, -num);
    }
}